<template>
	<!-- 操作栏 -->
	<el-input placeholder="请输入账号" v-model="inpWord" :value="inpWord" @keyup.enter="searchUserManager(1)"></el-input>
	<el-input placeholder="请输入角色" v-model="inpRole" :value="inpRole" @keyup.enter="searchUserManager(2)"></el-input>
	<el-button class="searchBtn" type='info' :icon="Search" @click="searchUserManagerClick">搜索</el-button>
	<el-button class="addBtn" type='info' :icon="CirclePlus" @click="addUser">添加</el-button>
	<!-- 表格 -->
	<el-table :data='tableData' style="height: 60vh;">
		<el-table-column label="账号" prop="userName" align="center"></el-table-column>
		<el-table-column label="角色"  align="center">
			<template #default="scope">
				<span v-for="(value, index) in tableData[scope.$index].roles" :key="index">{{ value.roleName }}</span>
			</template>
		</el-table-column>
		<el-table-column label="操作"  align="center">
			<template #default="scope">
				<span style="color: #77b24c; margin:0 10px; cursor: pointer;" @click="update(scope.row)">修改</span>
				<span style="color:#ff0000;margin:0 10px; cursor: pointer;" @click="del(scope.row.userId)">删除</span>
			</template>
		</el-table-column>
	</el-table>
	<el-pagination
		layout="prev,pager,next"
		:page-size="pageSize"
		:page-count="pageCount"
		v-model:current-page="pageIndex"	
		@current-change="changePage"
	></el-pagination>
	<!-- 添加 -->
	<el-dialog title="请添加新的用户" center v-model="addFlag" width="30%">
		<div class="FormBox">
			<el-form :model="formData" :rules="rules" ref="myForm" :hide-required-asterisk="true">
				<el-form-item label="账号:" prop="userName" >
					<el-input placeholder="请输入新的账号名" v-model="formData.userName"></el-input>
				</el-form-item>
				<el-form-item label="密码:" prop="pwd">
					<el-input placeholder="初始密码" type="password" v-model="formData.pwd"></el-input>
				</el-form-item>
				<el-form-item label="角色:" prop="roleName">
					<el-checkbox-group v-model="checkList">
					  <el-checkbox v-for="(x,index) in roleNameList" :label="x.roleName"  :value="x.roleId" :key="index">{{ x.roleName }}</el-checkbox> 
					</el-checkbox-group> 
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer ">
				<el-button  style="background-color:#106ab1 ; color: white;" @click="confirmAdd(myForm)">确 定</el-button>
				<el-button style="background-color: #999999; color:white" @click="cancel">取 消</el-button>
			</span>
		</div>
	</el-dialog>
	<!-- 修改 -->
	<el-dialog title="请修改当前用户信息" center v-model="updateFlag" width="30%">
		<div class="FormBox">
			<el-form :model="formData" :rules="rules" ref="myForm" :hide-required-asterisk="true">
				<el-form-item label="账号:" prop="userName">
					<el-input placeholder="原账号" v-model="formData.userName"></el-input>
				</el-form-item>
				<el-form-item label="密码:" prop="pwd">
					<el-input placeholder="初始密码" type="password" v-model="formData.pwd"></el-input>
				</el-form-item>
				<el-form-item label="角色:" prop="roleName">
					<el-checkbox-group v-model="RoleNames">
					  <el-checkbox v-for="(x,index) in roleNameList" :label="x.roleName"  :value="x.roleId" :key="index">{{ x.roleName }}</el-checkbox> 
					</el-checkbox-group> 
				</el-form-item>
			</el-form>
			<span slot="footer" class="dialog-footer ">
				<el-button  style="background-color:#106ab1 ; color: white;" @click="confirmAddforUpdate(myForm)">确 定</el-button>
				<el-button style="background-color: #999999; color:white" @click="cancel">取 消</el-button>
			</span>
		</div>
	</el-dialog>
	<!-- 删除 -->
	<el-dialog v-model="delFlag" width="30%">
		<div class="FormBox">
			<b style="margin-bottom: 10%;">确认删除该用户？</b>
			<span slot="footer" class="dialog-footer">
				<el-button @click="delOk" style="background-color:#106ab1; color: white;">确 定</el-button>
				<el-button @click="cancel" style="background-color: #999999; color:white"  >取 消</el-button>
			</span>
		</div>
	</el-dialog>
</template>

<script setup lang="ts">
	// el组件
	import { ElMessage} from 'element-plus';
	import {Search,CirclePlus} from '@element-plus/icons-vue'
	// 接口
	import {UserFind,searchUser,RolesList,adduser,updateuser,delateuser} from "../api/wqj/index";
	// ref等相关
	import { ref,shallowRef,reactive ,onMounted} from 'vue';
	// 类型注解
	import { formType } from '../modal/wqj/user';
	// 页面自定义变量
	let pageSize:any='5';//每页显示4条数据
	let pageIndex=ref<string>('1');//当前显示第0页
	let tableData=ref([]);//表格数据
	let pageCount=shallowRef<number>(0)//总页数
	let inpRole=ref<string>("");//角色输入框的值
	let inpWord=ref<string>("")//账号输入框的值
	let addFlag=ref<boolean>(false)//添加模态窗弹出
	let updateFlag=ref<boolean>(false)
	let roleNameList:any=[];//角色名称列表
	let RoleNames=ref([]);//权限名
	let roleIds=ref([]);//添加的权限id
	let checkList = ref([])//复选框选中内容
	let newUserId=ref("")//新的用户Id
	let originalName=ref("")//初始账号
	let originalRoleid=ref([])//初始角色
	let delFlag=ref<boolean>(false)//删除模态窗弹出
	let delUserId=ref("")//删除的userId
	let loginId=ref("")//当前登录的用户
	let myForm=ref(null)
	// 初始化表单
	let formData=reactive<formType>({
		userName:"",
		pwd:"",
		roleName:"",
	})
	// 验证规则
	let rules=reactive({
		userName:[{
			required:true,
			message:"账号名不为空",
			trigger:"blur",
		}],
		pwd:[{
			required:true,
			message:"密码不为空",
			trigger:"blur",
		},
		// 密码必须为6为数字
		{
			pattern: /^\d{6}$/,
			message: '请输入6位数字',
			 trigger: 'blur'
		}],
	})
	// 查询用户列表接口
	const showUserList=async()=>{
		let res=await UserFind({
			pageIndex:pageIndex.value,
			pageSize:pageSize,
		})
		// console.log("用户列表",res.list)
		tableData.value=res.list
		pageCount.value=Math.ceil(res.pageCount/pageSize)
	}
	// 搜索条件判断
	const searchConditon=async(index:number)=>{
		if(index==1){//账号搜索
			let res=await searchUser({
				pageIndex:pageIndex.value,
				pageSize:pageSize,
				userName:inpWord.value
			})
			tableData.value=res.list
			pageCount.value=Math.ceil(res.pageCount/pageSize)
		}else if(index==2){//角色搜索
			let res=await searchUser({
				pageIndex:pageIndex.value,
				pageSize:pageSize,
				roleName:inpRole.value
			})
			tableData.value=res.list
			pageCount.value=Math.ceil(res.pageCount/pageSize)
		}else{//账号+角色
			let res=await searchUser({
				pageIndex:pageIndex.value,
				pageSize:pageSize,
				userName:inpWord.value,
				roleName:inpRole.value
			})
			tableData.value=res.list
			pageCount.value=Math.ceil(res.pageCount/pageSize)
		}
	}
	// enter搜索
	const searchUserManager=(index:number)=>{
		pageIndex.value='1'
		if(inpWord.value!=''&&inpRole.value==''){// 账号
			searchConditon(1)
		}else if(inpWord.value==''&&inpRole.value!=''){// 角色
			searchConditon(2)
		}else{// 多条件
			searchConditon(3)
		}
	}
	// 单击搜索
	const searchUserManagerClick=()=>{
		pageIndex.value='1'
		if(inpWord.value!=''&&inpRole.value==''){// 账号
			searchConditon(1)
		}else if(inpWord.value==''&&inpRole.value!=''){// 角色
			searchConditon(2)
		}else{// 多条件
			searchConditon(3)
		}
	}
	// 切页
	const changePage=(page:string)=>{
		pageIndex.value=String(page);
		if(inpWord.value != "" && inpRole.value != ""){
			searchConditon(3)
		}else if (inpWord.value != "") {
			searchConditon(1)
		} else if (inpRole.value != "") {
			searchConditon(2)
		} else {
			showUserList()
		}
	}
	// 复选框--角色列表
	const showRoles=async()=>{
		let res=await RolesList({
			status:1
		})
		roleNameList=res
		// console.log("权限",roleNameList)
	}
	showRoles()
	// 添加--复选框选择
	const AddRoleId=()=>{
		for(var i=0;i<checkList.value.length;i++){
			// console.log("check",checkList.value)
			roleNameList.forEach(v=>{
				if(checkList.value[i]==v.roleId){
					roleIds.value.push(v.roleId)
				}
			})
		}
	}
	// 修改--复选框选择
	const UpdateRoleId=()=>{
		roleIds.value=[]
		for(var i=0;i<RoleNames.value.length;i++){
			roleNameList.forEach(v=>{
				if(RoleNames.value[i]==v.roleId){
					roleIds.value.push(v.roleId)
				}
			})
		}
	}
	// 弹出对话框
	const addUser=()=>{
		addFlag.value=true
	}
	// 点击确认添加用户
	const confirmAdd=(formEL)=>{
		AddRoleId()
		if(roleIds.value.length==0){//未选择角色
			ElMessage.error("请填写完整信息")
		}else{
			// console.log("formEl",formEL,formEL.validate)
			formEL.validate(async(valid)=>{
				if(valid){
					let res = await adduser({
						userName:formData.userName,
						pwd: formData.pwd,
						roleIds: roleIds.value
					})
					if(res==undefined){
						ElMessage.success("添加成功")
						showUserList()
						addFlag.value=false
					}else{
						ElMessage.error(res.msg)
					}
				}
			})
		}
	}
	// 点击取消关闭对话框
	const cancel=()=>{
		formData.userName=""
		formData.pwd=""
		checkList.value=[]
		RoleNames.value=[]
		addFlag.value=false
		updateFlag.value=false
		delFlag.value=false
	}
	// 修改弹出对话框
	const update=(item)=>{
		updateFlag.value=true
		console.log("本行的信息",item)
		// 回显账号和角色信息
		formData.userName=item.userName//账号
		formData.pwd=""//密码
		newUserId.value=item.userId//id
		originalName.value=item.userName
		item.roles.forEach(v=>{//角色
			RoleNames.value.push(v.roleId)
		})
		// 调用复选框选择
		UpdateRoleId()
		originalRoleid.value=roleIds.value
	}
	// 点击确认修改
	const confirmAddforUpdate=(formEL)=>{
		UpdateRoleId()
		if(roleIds.value.length==0){//未选择角色
			ElMessage.error("请填写完整信息")
		}else{
			var tempObj={}
			if(originalName.value!=formData.userName){//账号改变
				tempObj={
					userName: formData.userName,
					pwd: formData.pwd,
					userId: newUserId.value
				}
			}else{
				tempObj={
					userName: formData.userName,
					pwd: formData.pwd,
					roleIds:roleIds.value,
					userId: newUserId.value
				}
			}
			formEL.validate(async(valid)=>{
				if(valid){
					let res = await updateuser(tempObj)
					console.log("修改",res)
					if(res==undefined){
						ElMessage.success("修改成功")
						showUserList()
						updateFlag.value=false
					}else{
						ElMessage.error(res.msg)
					}
				}
			})
		}
	}
	// 删除
	const del=(item)=>{
		console.log(item)
		delFlag.value=true
		delUserId.value=item
	}
	const delOk=async()=>{
		if(loginId.value==delUserId.value){
			ElMessage.error("该账号处于登录状态，不能删除")
		}else{
			let res=await delateuser({
				userId:delUserId.value
			})
			if(res==undefined){
				ElMessage.success("用户删除成功")
				searchConditon(3)
				delFlag.value=false
			}else{
				ElMessage.error(res.msg)
			}
		}
	}
	onMounted(()=>{
		showUserList();
		loginId.value=sessionStorage.getItem("userId")//获取当前登录的用户id
	})
</script>

<style scoped lang="less">
	.el-input{
		width: 205px;
		margin-right: 10px;
		border: none;
	}
	.searchBtn{
		background-color: #106ab1;
		border: none;
	}
	.addBtn{
		background-color: #00a0e9;
		border: none;
		float: right;
		margin-right: 20px;
	}
	.el-table{
		margin-top: 20px;
	}
	.el-table{
		--el-table-border-color:none;
		--el-table-borde:none;
		--el-table-bg-color:none !important;    
		--el-table-header-bg-color:#f3f8fd;
		--el-table-header-text-color:#333 !important
	}
	/* 表格间隙 */
	:deep(.el-table__body) {
	  -webkit-border-vertical-spacing: 9px;
	}
	/* 分页样式 */
	.el-pagination{
		--el-pagination-bg-color:none;
		--el-pagination-button-disabled-bg-color:none;
		justify-content: center;
	}
	/* 表单样式 */
	.FormBox{
		width:100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		box-sizing: border-box;
		padding: 10% 0;
		.el-form{
			width:100%;
			height:30vh;
			display: flex;
			flex-direction: column;
			align-items: center;
			.el-form-item{
				width: 90%;
				.el-input{
					width:100%;
					height: 5vh;
				}
			}
		}
		.dialog-footer{
			width: 100%;
			display: flex;
			justify-content: center;
			// .el-button{
			// 	width:30%
			// }
		}
	}

</style>